package io.renren.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.constant.AppConstant;
import io.renren.dao.OnlineStudyDao;
import io.renren.entity.BmInfoEntity;
import io.renren.service.OnlineStudyService;
import io.renren.vo.RespModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * Created by ThinkPad on 2018/11/12.
 */
@Service
public class OnlineStudyServiceImpl implements OnlineStudyService{

    @Autowired
    private OnlineStudyDao onlineStudyDao;

    @Override
    public Map<String, Object> queryXybmInfo(String userId) {
        return onlineStudyDao.queryXybmInfo(userId);
    }

    @Override
    public Integer querySubscribeInfo(String userId) {
        return onlineStudyDao.querySubscribeInfo(userId);
    }

    @Override
    public List<Map<String,Object>> querySubscribeDateList(String startdate, String studytype, String address){
        return onlineStudyDao.querySubscribeDateList(startdate, studytype, address);
    }

    @Override
    public Map<String, Object> queryCreditscore(String userId) {
        return onlineStudyDao.queryCreditscore(userId);
    }

    @Override
    public Map<String, Object> queryBmxx(String userid){
        return onlineStudyDao.queryBmxx(userid);
    }

    @Override
    public void saveBmInfo(BmInfoEntity bmInfoEntity) {
        onlineStudyDao.saveBmInfo(bmInfoEntity);
    }

    @Override
    public Integer queryDryxSfxw(String xy_id){
        return onlineStudyDao.queryDryxSfxw(xy_id);
    }

    @Override
    public void updateSfxw(Map<String, String> paramMap) {
        onlineStudyDao.updateSfxw(paramMap);
    }

    @Override
    public Integer queryXxjlLearningTime(Map<String,Object> paramMap){
        return onlineStudyDao.queryXxjlLearningTime(paramMap);
    }

    @Override
    public List<Map<String,String>> queryStudyAddress(){
        return onlineStudyDao.queryStudyAddress();
    }

    public void updateAvatar(Map paramMap) {
        onlineStudyDao.updateAvatar(paramMap);
    }

    @Override
    public List<Map> queryXxjlById(String xy_id){
        return onlineStudyDao.queryXxjlById(xy_id);
    }

    @Override
    public List<Map> queryVideoList(){
        return onlineStudyDao.queryVideoList();
    }

    @Override
    public void saveStudyImg(Map paramMap) {
        onlineStudyDao.saveStudyImg(paramMap);
    }

    @Override
    public void updateDryx(Map paramMap) {
        onlineStudyDao.updateDryx(paramMap);
    }

    public List<Map<String,Object>> saveExamPaper(Map paramMap,String type) throws Exception{
        String examId = UUID.randomUUID().toString().replaceAll("-","");
        paramMap.put("id", examId);
        onlineStudyDao.insertExam(paramMap);
        Set<Map<String,Object>> examSet = new HashSet<>();
        List<Map<String,Object>> examDetailList = new ArrayList<Map<String,Object>>();
        if("1".equals(type)){
            //1、获取当前题题目数量
            int count = 15;
            //试卷详情
            while(examSet.size()<10){
                Random random = new Random();
                int quesNum = random.nextInt(count);
                Map questionByNum = onlineStudyDao.getQuestionByNum(quesNum);
                examSet.add(questionByNum);
            }
            examDetailList.addAll(examSet);
            for(int i= 0;i<examDetailList.size();i++){
                Map<String,Object> quesMap = examDetailList.get(i);
                StringBuffer correctAnswer = new StringBuffer();
                boolean isAnswerA = MapUtils.getString(quesMap, "is_answer_a","").equals("true");
                boolean isAnswerB = MapUtils.getString(quesMap, "is_answer_b","").equals("true");
                boolean isAnswerC = MapUtils.getString(quesMap, "is_answer_c","").equals("true");
                boolean isAnswerD = MapUtils.getString(quesMap, "is_answer_f","").equals("true");

                correctAnswer.append(isAnswerA ? "A,":"")
                        .append(isAnswerB ? "B,":"")
                        .append(isAnswerC ? "C,":"")
                        .append(isAnswerD ? "D":"");

                Map examDetail = new HashMap();
                examDetail.put("id", UUID.randomUUID().toString().replaceAll("-",""));
                examDetail.put("examId", examId);
                examDetail.put("questionId", MapUtils.getObject(quesMap, "id"));
                examDetail.put("correctAnswer", correctAnswer.toString());
                onlineStudyDao.insertExamDetail(examDetail);
            }
        }else if("4".equals(type)){

        }
        return examDetailList;
    }

    public Map<String, Object> calcScore(String userid, String examdId, String questionList) {
        final int[] score = {0};
        JSONArray quesListArr = JSONArray.parseArray(questionList);
        Iterator<Object> iterator = quesListArr.iterator();
        iterator.forEachRemaining((object)->{
            JSONObject jsonObj = (JSONObject) object;
            String id = jsonObj.getString("id");
            //用户选择的答案
            String uAnswer = jsonObj.getString("uAnswer");

            Map<String, Object> quesMap = onlineStudyDao.getQuestionById(id);
            String realAnswer = MapUtils.getString(quesMap, "ques_answer");
            if(StringUtils.isNotBlank(realAnswer)){
                realAnswer = realAnswer.substring(0,realAnswer.length() - 1);
            }

            if(realAnswer.equals(uAnswer)){
                score[0] += 1;
            }
        });

        Map scoreMap = new HashMap();
        scoreMap.put("examId", examdId);
        scoreMap.put("score", score[0]);
        scoreMap.put("userId", userid);
        onlineStudyDao.updateExamScore(scoreMap);
        return scoreMap;
    }


    /**
     * 用户开始学习
     * @param paramMap
     * @return
     */
    public RespModel ksxx(Map paramMap) {
        int final_learn_time = paramMap.get("bmlx").equals("0") ? 240 : 180;
        Map queryXxjlLatest = onlineStudyDao.queryXxjlLatest((String) paramMap.get("xy_id"));
        //1、查询学习记录为空则插入新的学习记录
        if(queryXxjlLatest == null || queryXxjlLatest.isEmpty()) {
            insertXxjl(paramMap);
            return new RespModel(AppConstant.STATU_SUCCESS.getName(),
                    AppConstant.STATU_SUCCESS.getValue(), "学习记录生成成功！", null);
        }
        String xxdate = (String) queryXxjlLatest.get("xxdate");
        Integer latest_learn_time = Integer.valueOf((String) queryXxjlLatest.get("dryx"));
        if(latest_learn_time<final_learn_time && !xxdate.equals(LocalDate.now().toString())){
            //2、最新的学习日期不是今天，且学时未满，则删除已有的学习记录
            onlineStudyDao.delDiscontentedXxjl(paramMap);
            insertXxjl(paramMap);
            return new RespModel(AppConstant.STATU_SUCCESS.getName(),
                    AppConstant.STATU_SUCCESS.getValue(), "学习记录生成成功！", null);
        }
        else{//3、递归查询达标学习记录
            int recursive_count = recursiveXxjl(queryXxjlLatest, 1, final_learn_time);
            if(recursive_count ==3){
                //4、已连续学习达标3天
                return new RespModel(AppConstant.THINGS_HAVE_BEAN_DONE.getName(),
                        AppConstant.THINGS_HAVE_BEAN_DONE.getValue(),
                        "已学够学时，将不再记录学习时间",
                        null);
            }
            else{//5、未连续达标，连续两天或者1天
                if (!xxdate.equals(LocalDate.now().toString()) &&
                        !xxdate.equals(LocalDate.now().minusDays(1).toString())) {
                    //已存在的学习记录无法再连续达标，删除已有的学习记录
                    onlineStudyDao.delDiscontentedXxjl(paramMap);
                    insertXxjl(paramMap);
                    return new RespModel(AppConstant.STATU_SUCCESS.getName(),
                            AppConstant.STATU_SUCCESS.getValue(), "学习记录生成成功！", null);
                }
                else if (xxdate.equals(LocalDate.now().toString())) {
                    if (latest_learn_time >= final_learn_time) {
                        return new RespModel(AppConstant.THINGS_HAVE_BEAN_DONE.getName(),
                                AppConstant.THINGS_HAVE_BEAN_DONE.getValue(),
                                "您已学够学时，将不再记录学习时间",
                                null);
                    }
                    else{
                        //判断当前剩余时间加上已学习时间能否达到学时
                        LocalDateTime past_LocalDateTime = LocalDateTime.now().minusMinutes(latest_learn_time);
                        LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0) .withSecond(0).withNano(0);
                        long between = ChronoUnit.MINUTES.between(past_LocalDateTime, midnight);
                        if (between < final_learn_time) {
                            return new RespModel(AppConstant.CONDITION_NOT_SATISFIED.getName(),
                                    AppConstant.CONDITION_NOT_SATISFIED.getValue(),
                                    "今日学习时间不足，将不记录学习时间",
                                    null);
                        }else{
                            return new RespModel(AppConstant.STATU_SUCCESS.getName(),
                                    AppConstant.STATU_SUCCESS.getValue(), "学习记录已存在,可继续学习", null);
                        }
                    }
                }else{//最新的学习日期是昨天，则生成今天的学习记录
                    insertXxjl(paramMap);
                    return new RespModel(AppConstant.STATU_SUCCESS.getName(),
                            AppConstant.STATU_SUCCESS.getValue(), "学习记录生成成功", null);
                }
            }
        }
    }

    /**
     * 递归查询学习记录，并清楚不符合条件的学习记录
     * @param paramMap
     * @param loopfrequency
     * @param final_learn_time
     */
    private int recursiveXxjl(Map paramMap,int loopfrequency,int final_learn_time){
        if(loopfrequency >2) return loopfrequency;
        String xxdate = (String) paramMap.get("xxdate");
        LocalDate xxjl_xxdate = LocalDate.parse(xxdate);
        paramMap.put("xxdate", xxjl_xxdate.minusDays(loopfrequency).toString());
        Integer beforeDay_learn_time = onlineStudyDao.queryXxjlLearningTime(paramMap);
        if (beforeDay_learn_time != null && beforeDay_learn_time >= final_learn_time) {
            return recursiveXxjl(paramMap, loopfrequency ++, final_learn_time);
        }else {
            return loopfrequency;
        }
    }

    /**
     * 生成今天的学习记录
     * @param paramMap
     */
    private void insertXxjl(Map paramMap) {
        //插入学习记录
        paramMap.put("xxdate", LocalDate.now().toString());
        paramMap.put("dryx",0);
        onlineStudyDao.insertXxjl(paramMap);
    }

    @Override
    public List<Map> queryXxjlImage(String xy_id, String video_id) {
        return onlineStudyDao.queryXxjlImage(xy_id, video_id);
    }
}
